package com.umeox.watch.moto.chat.provider

import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import androidx.sqlite.db.SupportSQLiteDatabase
import com.umeox.moto.common.log.Logger
import com.umeox.watch.moto.chat.base.BaseApp
import com.umeox.watch.moto.chat.db.AppDatabase
import com.umeox.watch.moto.chat.db.ContactInfo
import com.umeox.watch.moto.chat.db.ContactInfoDao
import com.umeox.watch.moto.dataservice.DataProvider
import java.lang.Exception
import java.lang.IllegalArgumentException
import java.util.HashMap

/**
 * Created by Rambo 2021/8/20
 * Describe:
 */
class ChatContactProvider : ContentProvider() {

    //访问表的所有列
    private val CHAT_CONTACT_COLLECTION = 1

    //访问单独的列
    private val CHAT_CONTACT_INFO = 2

    //访问单独的列
    private val CHAT_CONTACT_UNREAD_COUNT = 3

    //为数据库表字段起别名
    private var userProjectionMap: HashMap<String, String> = HashMap<String, String>()

    init {
        userProjectionMap[DataProvider.ChatContactProvider.FRIEND_ID] =
            DataProvider.ChatContactProvider.FRIEND_ID
        userProjectionMap[DataProvider.ChatContactProvider.NAME] =
            DataProvider.ChatContactProvider.NAME
        userProjectionMap[DataProvider.ChatContactProvider.IS_ADMIN] =
            DataProvider.ChatContactProvider.IS_ADMIN
        userProjectionMap[DataProvider.ChatContactProvider.AVATAR] =
            DataProvider.ChatContactProvider.AVATAR
        userProjectionMap[DataProvider.ChatContactProvider.LAST_CONTACT_TIME] =
            DataProvider.ChatContactProvider.LAST_CONTACT_TIME
        userProjectionMap[DataProvider.ChatContactProvider.LAST_MESSAGE_ID] =
            DataProvider.ChatContactProvider.LAST_MESSAGE_ID
        userProjectionMap[DataProvider.ChatContactProvider.MISS_COUNT] =
            DataProvider.ChatContactProvider.MISS_COUNT
    }

    private val URI_MATCHER = UriMatcher(UriMatcher.NO_MATCH)

    override fun onCreate(): Boolean {
        Logger.i(">>>>>>>>onCreate<<<<<<<<<<")
        URI_MATCHER.addURI(
            DataProvider.ChatContactProvider.AUTHORITY,
            "/ContactInfo",
            CHAT_CONTACT_COLLECTION
        )
        URI_MATCHER.addURI(
            DataProvider.ChatContactProvider.AUTHORITY,
            "/ContactInfo/#",
            CHAT_CONTACT_INFO
        )
        URI_MATCHER.addURI(
            DataProvider.ChatContactProvider.AUTHORITY,
            "/ContactInfo/unreadCount",
            CHAT_CONTACT_UNREAD_COUNT
        )
        return true
    }

    override fun getType(uri: Uri): String? {
        var type: String? = null
        type = when (URI_MATCHER.match(uri)) {
            CHAT_CONTACT_COLLECTION -> "vnd.android.cursor.dir/contacts"
            CHAT_CONTACT_INFO -> "vnd.android.cursor.dir/contact"
            CHAT_CONTACT_UNREAD_COUNT -> "vnd.android.cursor.item/unread_count"
            else -> throw IllegalArgumentException("this is unkown uri:$uri")
        }
        return type
    }

    /**
     * * 插入数据
     */

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        val database: SupportSQLiteDatabase = AppDatabase.get().openHelper.writableDatabase
        try {
            val uid = values!!.getAsString(DataProvider.ChatContactProvider.FRIEND_ID)

            var contact: ContactInfo? = AppDatabase.get().contactInfoDao().queryByFriendId(uid)
            if (contact == null) {
                contact = ContactInfo()
            }
            database.beginTransaction()
            contact.friendId = values.getAsString(DataProvider.ChatContactProvider.FRIEND_ID)
            contact.type = values.getAsInteger(DataProvider.ChatContactProvider.FRIEND_TYPE)
            contact.name = (values.getAsString(DataProvider.ChatContactProvider.NAME))
            contact.avatar = (values.getAsString(DataProvider.ChatContactProvider.AVATAR))
            contact.isAdmin = (values.getAsBoolean(DataProvider.ChatContactProvider.IS_ADMIN))
            contact.createTime = (values.getAsInteger(DataProvider.ChatContactProvider.CREATE_TIME))
            contact.isGroup = (values.getAsBoolean(DataProvider.ChatContactProvider.IS_GROUP))
            AppDatabase.get().contactInfoDao().save(contact)
            database.setTransactionSuccessful()
            return ContentUris.withAppendedId(uri, 1)
        } catch (e: Exception) {
            Log.e("device_launcher", "ChatContactProvider insert: ", e)
        } finally {
            database.endTransaction()
            DataProvider.ChatContactProvider.notifyChange()
        }
        return null
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        val contactInfoDao: ContactInfoDao = AppDatabase.get().contactInfoDao()
        val contactList: List<ContactInfo>? = contactInfoDao.loadAllContacts()
        if (contactList!!.isNotEmpty()) {
            try {
                for (contactInfo in contactList) {
                    if (contactInfoDao.delete(contactInfo) > 0) {
                        AppDatabase.get().chatMessageDao().deleteByFriendId(contactInfo.friendId)
                    }
                }
            } catch (ignored: Exception) {
            }
        }
        return 0
    }

    override fun update(
        uri: Uri, values: ContentValues?, selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        if (values == null) {
            Logger.w("ChatProvider update values null")
            return 0
        }
        val uid = values.getAsString(DataProvider.ChatContactProvider.FRIEND_ID)
        val database: SupportSQLiteDatabase = AppDatabase.get().openHelper.writableDatabase

        val contact: ContactInfo? = AppDatabase.get().contactInfoDao().queryByFriendId(uid)
        val count: Int
        var _selection = ""
        database.beginTransaction()
        if (contact != null) {
            if (TextUtils.isEmpty(selection)) {
                _selection = "id = " + contact.id
            }
            count = database.update(
                "contact_info", 0,
                values,
                _selection,
                selectionArgs
            )
        } else {
            count = database.insert("contact_info", SQLiteDatabase.CONFLICT_NONE, values).toInt()
        }
        database.setTransactionSuccessful()
        database.endTransaction()
        return if (count > 0) 1 else 0
    }

    override fun query(
        uri: Uri,
        projection: Array<String?>?,
        selection: String?,
        selectionArgs: Array<String?>?,
        sortOrder: String?
    ): Cursor? {
        //创建一个执行查询的Sqlite
        val qb = SQLiteQueryBuilder()
        var sql = ""

        //设置排序
        val orderBy: String? = if (TextUtils.isEmpty(sortOrder)) {
            "id DESC"
        } else {
            sortOrder
        }
        when (URI_MATCHER.match(uri)) {
            CHAT_CONTACT_COLLECTION -> {
                //设置要查询的表名
                qb.tables = "contact_info"
                //设置表字段的别名
                qb.projectionMap = userProjectionMap
                sql = qb.buildQuery(projection, selection, null, null, orderBy, null)
            }
            CHAT_CONTACT_INFO -> {
                qb.tables = "contact_info"
                qb.projectionMap = userProjectionMap
                //追加条件,getPathSegments()得到用户请求的Uri地址截取的数组，get(1)得到去掉地址中/以后的第二个元素
                val arg = uri.pathSegments[1]
                sql = qb.buildQuery(
                    null,
                    "id =$arg",
                    null,
                    null,
                    orderBy,
                    null
                )
            }
            CHAT_CONTACT_UNREAD_COUNT -> {
                qb.tables = "contact_info"
                sql = qb.buildQuery(
                    arrayOf("SUM(missCount)  AS totalCount"),
                    "missCount > 0",
                    null,
                    null,
                    orderBy,
                    null
                )
                Logger.i("查询未读语聊消息条数SQL：$sql")
            }
            else -> Logger.e("URI不匹配")
        }
        return try {
            //执行查询，把输入传入
            val c: Cursor =AppDatabase.get().query(sql, selectionArgs)
            //设置监听
            c.setNotificationUri(BaseApp.getContext().applicationContext.contentResolver, uri)
            c
        } catch (e: Exception) {
            Logger.e(e.toString())
            null
        }
    }
}